package com.example.question.dp.dp2;

import java.util.HashMap;
import java.util.Map;

public class Code10_494 {
    public static void main(String[] args) {
        Code10_494 code = new Code10_494();
        int ways = code.findTargetSumWays(new int[]{1, 1, 1, 1, 1}, 3);
        System.out.println("ways = " + ways);
    }

    public int findTargetSumWays(int[] nums, int target) {
//        int[][] memo = new int[nums.length][target + 1];
        Map<String, Integer> map = new HashMap<>();
        return dfs(nums, target, 0, map);
    }

    private int dfs(int[] nums, int target, int index, Map<String, Integer> map) {
        if (index == nums.length) {
            if (target == 0) {
                return 1;
            } else {
                return -1;
            }
        }
        String key = index + "#" + target;
        if (map.containsKey(key)) {
            return map.get(key);
        }

        int res = 0;
        int num1 = dfs(nums, target - nums[index], index + 1, map);
        int num2 = dfs(nums, target + nums[index], index + 1, map);
        if (num1 != -1) {
            res += num1;
        }
        if (num2 != -1) {
            res += num2;
        }
        map.put(key, res);
        return map.get(key);
    }

    private int dfs1(int[] nums, int target, int index, Map<String, Integer> map) {
        if (index == nums.length) {
            if (target == 0) {
                return 1;
            } else {
                return -1;
            }
        }
        String key = index + "#" + target;
        if (map.containsKey(key)) {
            return map.get(key);
        }

        int res = 0;
        int num1 = dfs1(nums, target - nums[index], index + 1, map);
        int num2 = dfs1(nums, target + nums[index], index + 1, map);
        if (num1 != -1) {
            res += num1;
        }
        if (num2 != -1) {
            res += num2;
        }
        map.put(key, res);
        return map.get(key);
    }
}
